

package com.example.testandroid;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;

import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Xml.Encoding;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.*;
import com.facebook.model.GraphObject;

import com.facebook.model.GraphUser;
import com.facebook.widget.*;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.doubleclick.AppEventListener;
import com.google.android.gms.ads.doubleclick.PublisherAdRequest;
import com.google.android.gms.ads.doubleclick.PublisherAdView;









public class PlayActivity extends FragmentActivity {

	private static final String LOG_TAG = "Ads";
	public final static int REQUEST_CODE_SC = 1;
	public final static int EARN_POINT_SC = 2;
	int _layoutWidth = 0;
	int _nextIndex = 0;
	static int _currentScore = 0;
	public int _numberKnownWords = 0;
	public int _numberHelpWords= 0;
	public static Boolean isEarnPointOk = false;
	
	String _displayText = null;
	String _expectText = null;
	String _suggestionText = null;
	List<Integer> _listDisplayButtonsId = new ArrayList<Integer>();;
	List<Integer> _listRepondSuggestButtionId = new ArrayList<Integer>();
	Animation _myAnimation = null;
	TextView _tvQuestion = null;
	
	Button _btIscore = null;
	RelativeLayout displayTest_layout = null;
	
	  /** Your ad unit id. Replace with your actual ad unit id. */
	  private static final String AD_UNIT_ID = "ca-app-pub-4105375449899778/5606132641";

	  /** The interstitial ad. */
	  private InterstitialAd interstitialAd;
	  
	  private boolean  isAdsReady = false;
	  
	  /** The view to show the ad. */
	  private PublisherAdView adView;
	  
	  
	  MediaPlayer mrejectword,maddword,mplaygame;
	  private Boolean bsound = true;
	  
	  
	
	
	private Button _showAddButton;
	private Button _soundButton;
	
	
    private static final String PERMISSION = "publish_actions";


    public PlayActivity keepit = null;
    private final String PENDING_ACTION_BUNDLE_KEY = "com.example.testandroid:PendingAction";
    private Button _postPhotoButton;

    private PendingAction pendingAction = PendingAction.NONE;
   // private ViewGroup controlsContainer;
    
	

    private boolean _canPresentShareDialogWithPhotos;

    private enum PendingAction {
        NONE,
        POST_PHOTO
    }
    private UiLifecycleHelper uiHelper;

  
    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };
    

    private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
            Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
            Log.d("HelloFacebook", "Success!");
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
            pendingAction = PendingAction.valueOf(name);
        }
        setContentView(R.layout.activity_facebook);
        
        mrejectword=MediaPlayer.create(this,R.raw.srejectword);
        maddword=MediaPlayer.create(this,R.raw.sclickbutton);
        mplaygame=MediaPlayer.create(this,R.raw.sgame);
	  
        // Create an ad.
        //interstitialAd = new InterstitialAd(this);
        //interstitialAd.setAdUnitId(AD_UNIT_ID);     
        //interstitialAd.setAdListener(new LoggingAdListener());
        
        //adView = new PublisherAdView(this);
       // adView.setAdUnitId("ca-app-pub-4105375449899778/5215853049");
       // adView.setAdSizes(AdSize.BANNER, AdSize.MEDIUM_RECTANGLE, new AdSize(120, 20));
        
       // adView.setAdSizes(AdSize.BANNER);
       // adView.setAdSizes(new AdSize(120, 20));
        /** The implementation below is the same for all examples. */
        // Set the AdListener to listen for standard ad events.
        //adView.setAdListener(new LoggingAdListener());
       // adView.setPaddingRelative(30, 300, 150, 400);

      
        
        
        
        
		_listDisplayButtonsId = new ArrayList<Integer>();	
		
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		_layoutWidth = displaymetrics.widthPixels;
		_tvQuestion =  (TextView)findViewById(R.id.txQuestion);
		_tvQuestion.setWidth(_layoutWidth/5*4);
		
        _myAnimation = AnimationUtils.loadAnimation(this, R.anim.myanimation);

        _btIscore = (Button) findViewById(R.id.biscore);
        displayTest_layout = (RelativeLayout)findViewById(R.id.ifacebookLayout);
        
        _showAddButton = (Button)findViewById(R.id.btEarnPoints);
        _showAddButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	ShowEarnPoints();
            }
        });
        
        
        _postPhotoButton = (Button) findViewById(R.id.postPhotoButton);
        _postPhotoButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onClickPostPhoto();
            }
        });

        // Can we present the share dialog for photos?
        _canPresentShareDialogWithPhotos = FacebookDialog.canPresentShareDialog(this,
                FacebookDialog.ShareDialogFeature.PHOTOS);
        
        
        // Add code to print out the key hash
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.example.testandroid", 
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
                }
        } catch (NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
        
        display();
        
        // Lookup your LinearLayout assuming it’s been given the attribute
        // android:id="@+id/mainLayout".
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.ifacebookLayout);

        _soundButton = (Button)findViewById(R.id.btsound);
        // Add the adView to it.
       // layout.addView(adView,
           // new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        // Initiate an request to load the AdView with an ad.
       // adView.loadAd(new PublisherAdRequest.Builder()
        		//.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        		//.build());
        
       // loadInterstitial();
    }
    
    public void updatesoundstatus(View v)
    {
    	if (bsound)
    	{
    		bsound = false;
    		if (_soundButton != null)
    			_soundButton.setBackgroundResource(R.drawable.icsoff);
    		
    	}
    	else
    	{
    		bsound = true;
    		if (_soundButton != null)
    			_soundButton.setBackgroundResource(R.drawable.icson);
    	}
    }
    
    private void ShowEarnPoints()
    {
    	Intent i=new Intent(this, AdsActivity.class);
		startActivityForResult(i, EARN_POINT_SC);    	
    }
    
    public void helpshow(View v)
    {
    	isEarnPointOk = false;
    	 //Put up the Yes/No message box
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder
    	.setTitle(R.string.helpDialogTitle)
    	.setMessage(R.string.helpDialogText)
    	.setIcon(android.R.drawable.ic_dialog_alert)
    	.setPositiveButton(R.string.dongy, new DialogInterface.OnClickListener() {
    	    public void onClick(DialogInterface dialog, int which) {			      	
    	    	//Yes button clicked, do something
    	    	
    	    	PlayActivity.this.getTextHelp();
    	    	
    	   
    	    	
    	    	
    	    }
    	})
    	.setNegativeButton(R.string.thoat, null)						//Do nothing on no
    	.show();
    	//Log.e("test", "getText3");
    
    }
    
    public void getTextHelp()
    {
    	
    	if(_currentScore > 4)
    	{
    		
    		_currentScore -= 4;    		
    		_numberHelpWords += 1;
    		_numberKnownWords = _numberHelpWords;
    		
    		
    		RemoveButtons();
    		AddButtons(_expectText);
    		addSuggestButtons(_suggestionText);
    		displayScore();
    	}
    	else
    	{
    		Toast.makeText(PlayActivity.this, R.string.khongdupoint, 
                    Toast.LENGTH_SHORT).show();
    	}
    	
    }
    
    

    @Override
    protected void onResume() {
        super.onResume();
        uiHelper.onResume();

        // Call the 'activateApp' method to log an app event for use in analytics and advertising reporting.  Do so in
        // the onResume methods of the primary Activities that an app may be launched into.
        AppEventsLogger.activateApp(this);

        updateUI();
        
        if (adView != null) {
            adView.resume();
          }
       // showInterstitial();
    }
    
    @Override
    public void onPause() {
    	
    	 if (adView != null) {
             adView.pause();
           }
         
        super.onPause();
        uiHelper.onPause();

        // Call the 'deactivateApp' method to log an app event for use in analytics and advertising
        // reporting.  Do so in the onPause methods of the primary Activities that an app may be launched into.
       
        AppEventsLogger.deactivateApp(this);
    }

    @Override
    public void onDestroy() {
    	
    	  if (adView != null) {
              adView.destroy();
            }
        super.onDestroy();
        uiHelper.onDestroy();
    }
    
    
    

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);

        outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
	    if (requestCode == REQUEST_CODE_SC) {
	        if (resultCode == RESULT_OK) {
	            // No result found
	        	RemoveButtons();
	        	display();
	        }
	    }
	    
	    if (requestCode == EARN_POINT_SC) {
	        displayScore();
	    }
	    
		
    
    }


    
    
    //Game section//////////////////////////////////////////////////////
	public int loadIndex(){
		
		String FILENAME = "storefile";
		_currentScore = 0;
		try
		{
			FileInputStream fis = openFileInput(FILENAME);		
			byte[] dataArray;
			try {
				dataArray = new byte[fis.available()];
				String read_data = null;
				while (fis.read(dataArray) != -1) {
					read_data = new String(dataArray);
				}				
				fis.close();
				String[] stArray = read_data.split(";");
				
				int ntest = Integer.parseInt(stArray[0]);
				if (stArray.length > 1)
					_currentScore = Integer.parseInt(stArray[1]);
					
				return ntest;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return 0;
			}	
		
			
		}
		catch(FileNotFoundException e)
		{
			return 0;
		}	
	}
	
	public void saveIndex(int nidex){
		
		String data = Integer.toString(nidex) + ";" + Integer.toString(_currentScore);
		int len = data.length();

		if (len == 0) {
		
			return;

		} else {
			try {
				String FILENAME = "storefile";
				FileOutputStream fos = openFileOutput(FILENAME,
						Context.MODE_PRIVATE);
				fos.write(data.getBytes());
				fos.close();			

			} catch (FileNotFoundException e) {

				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			}
		}
	}
	
	private void displayScore()
	{
		if (_btIscore != null)
		{
			_btIscore.setText("" + Integer.toString(_currentScore));
			Log.e("test", "dispay score");
		}
		else
		{
			Log.e("test", "Not dispay score");
			
		}
	}
	
	
	public void display() {
		
		int index = loadIndex();		
		

		try 
		{
			InputStream fis = getResources().openRawResource(R.raw.textin);
			
			byte[] dataArray = new byte[fis.available()];
			
			
			BufferedReader in = new BufferedReader(new InputStreamReader(fis, "UTF8")); 
			
			String read_data = "";
				
			String line = "";
			while((line = in.readLine()) != null) {
				
				read_data = read_data + "/n" + line;
				
			    if (read_data.equals("")) {
			        System.out.println("Found an empty line at end of file.");
			    }
			}
			fis.close();
			
			
			String[] strArrayQuestion = read_data.split("<question name");
			if(strArrayQuestion.length < 3)
				return; //message here to tell that there is no question in data
			
			for (int iquestion = 1; iquestion < strArrayQuestion.length -1; iquestion++)
			{
				
			}
			
			//TextView tv2 = (TextView)findViewById(R.id.txQuestion);
			//tv2.setText(strArrayQuestion[1] + " " + Integer.toString(index));
			
			//if (true)
			//	return;
			if (index > strArrayQuestion.length -2)
			{
				_nextIndex = 0;
				index = strArrayQuestion.length -2;
			}
			else
			{
				_nextIndex = index + 1;
			}
			
			read_data = strArrayQuestion[index + 1];
			
			
			String[] strArray = read_data.split(";");		
			if (strArray.length > 1 && strArray[0].contains(">"))
			{
				
				
				String strnum = strArray[0].replace("=", "");
				strnum = strnum.replace("\"", "");
				strnum = strnum.replace(">", "");
				
				//TextView tv = (TextView)findViewById(R.id.txQuestion);
				//tv.setText(strnum);
				//if (true)
					//return;
				
				if (Integer.parseInt(strnum) == index)
				{
					
					String mytext = strArray[1];
					String mySugetText = strArray[2];
					
					displayScore();
					

					
					_tvQuestion.setText(strArray[3]);
					
					
					AddButtons(mytext);
					addSuggestButtons(mySugetText);
					
					
					fis.close();
					return;
				}
				
				
				
			}
			
			
			
		

			
			
			
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}	

	}
	
	private void AddButtons(String textin){
		String notSpaces = textin.replace(" ","").trim();
		int charnumber = notSpaces.length();
		int butWide = 33;
		int leftDis = 15;
		int betDis =  3;
		int topDis = _layoutWidth/6*5;
		int numberButtonOnRow = 6;
		
		_expectText = notSpaces;
		
		_displayText = String.format(Locale.US, "%0" + Integer.toString(charnumber) + "d", 0);
		_listRepondSuggestButtionId.clear();	
		
		int iRow = 0;
		int iCol = 0;
		
		int remainNumberBt = charnumber - (numberButtonOnRow*iRow);
		int realNumberBtOnCurrentRow = remainNumberBt < numberButtonOnRow? remainNumberBt: numberButtonOnRow;
		leftDis = (_layoutWidth - realNumberBtOnCurrentRow *(butWide + betDis)  + betDis)/2;

		for (int i = 0; i < charnumber && displayTest_layout != null; i++)
		{
			_listRepondSuggestButtionId.add(-1);
			
		
			//Log.e("test", "Inside add");
			 if (iCol >= numberButtonOnRow)
			 {
			    	iRow += 1;
			    	iCol = 0;
			    	
			    	
					remainNumberBt = charnumber - (numberButtonOnRow*iRow);
					realNumberBtOnCurrentRow = remainNumberBt < numberButtonOnRow? remainNumberBt: numberButtonOnRow;
					leftDis = (_layoutWidth - realNumberBtOnCurrentRow *(butWide + betDis)  + betDis)/2;
				
			 }
			 
			Button myButton = new Button(this);
			myButton.setId(i);
		    final int id_ = myButton.getId();		    
			myButton.setText("");			
	        RelativeLayout.LayoutParams layoutParams = new  RelativeLayout.LayoutParams(butWide, butWide);
		    layoutParams.setMargins(leftDis + iCol*(betDis + butWide), topDis + iRow*(butWide + betDis), 0, 0);
		    //Log.e("test", "Inside add: " + Integer.toString(leftDis + iCol*(betDis + butWide)));
		    myButton.setLayoutParams(layoutParams);	 
		    myButton.setLeft(leftDis + iCol*(betDis + butWide));
		    myButton.setBackgroundColor(Color.parseColor("#655c64"));
		    myButton.setTextColor(Color.BLUE);
		    myButton.setTypeface(null, Typeface.BOLD);
		  		    
		    displayTest_layout.addView(myButton);
		    
		    final Button btn1 = ((Button) displayTest_layout.findViewById(id_));
		    if (i < _numberHelpWords)
		    {
		    	//Log.e("test", _expectText + String.format(";%d %s", i, _expectText.charAt(i)));
		    	btn1.setText(String.format("%s", _expectText.charAt(i)));
		    	myButton.setTextColor(Color.CYAN);
		    	_displayText = setCharAtIndex(_displayText, i, _expectText.charAt(i));  
		    }
		    else
		    {
			    btn1.setOnClickListener(new View.OnClickListener() {
			        public void onClick(View view) {
			        	try
			        	{
			        		if (_displayText.charAt(id_) != '0' && _listRepondSuggestButtionId.get(id_) != -1 && id_ >= _numberHelpWords)
			        		{
			        			Button btsg = ((Button) findViewById(_listRepondSuggestButtionId.get(id_)));
			        			if (btsg != null)
			        			{				
			        				
			        				_displayText = setCharAtIndex(_displayText, id_, '0');    					
			        				
			        				btn1.setText("");
			        				btsg.setVisibility(View.VISIBLE);
			        				mrejectword.start();
			        				
			        			}
			        			
			        		}
			        		
			        		
			        	}
			        	catch(SecurityException e)
			        	{
			        		
			        	}
			        }
			    });
		    }
		    
		    iCol += 1;
		}
	}
	
	private void addSuggestButtons(String textin){
		String notSpaces = textin.replace(" ","").trim();
		int charnumber = notSpaces.length();
		int butWide = 42;
		int leftDis = 6;
		int betDis =  3;
		int topDis = _layoutWidth/6*5 + 70;
		int numberButtonOnRow = 6;
		_suggestionText = notSpaces;	
		
		int iRow = 0;
		int iCol = 0;
		
		int remainNumberBt = charnumber - (numberButtonOnRow*iRow);
		int realNumberBtOnCurrentRow = remainNumberBt < numberButtonOnRow? remainNumberBt: numberButtonOnRow;
		leftDis = (_layoutWidth - realNumberBtOnCurrentRow *(butWide + betDis)  + betDis)/2;
		
		for (int i = 0; i < charnumber && displayTest_layout != null; i++)
		{
		
			 if (iCol >= numberButtonOnRow)
			 {
		    	iRow += 1;
		    	iCol = 0;
		    	
		    	remainNumberBt = charnumber - (numberButtonOnRow*iRow);
				realNumberBtOnCurrentRow = remainNumberBt < numberButtonOnRow? remainNumberBt: numberButtonOnRow;
				leftDis = (_layoutWidth - realNumberBtOnCurrentRow *(butWide + betDis)  + betDis)/2;

			 }
			 
			Button myButton = new Button(this);
			myButton.setId(i + 100);
		    final int id_ = myButton.getId();     
			
			myButton.setText(Character.toString(notSpaces.charAt(i)));			
	        RelativeLayout.LayoutParams layoutParams = new  RelativeLayout.LayoutParams(butWide, butWide);
		    layoutParams.setMargins(leftDis + iCol*(betDis + butWide), topDis + iRow*(butWide + betDis), 0, 0);		    
		    myButton.setLayoutParams(layoutParams);	  
		    
		    displayTest_layout.addView(myButton);
		    
		    final Button btn1 = ((Button) findViewById(id_));
		    btn1.setOnClickListener(new View.OnClickListener() {
		        public void onClick(View view) {
		        	try
		        	{
		        		//TextView tv2 = (TextView) findViewById(R.id.textView1);
        				//tv2.setText(_displayText);
		        		for(int j =0; j < _displayText.length(); j++)
		        		{
		        			if(_displayText.charAt(j) == '0')
		        			{
		        				_listRepondSuggestButtionId.set(j, id_);
		        				
		        				_displayText = setCharAtIndex(_displayText, j, btn1.getText().charAt(0));		        				
		        			
		        				Button btDl = ((Button) findViewById(j));
		        				if (btDl != null)
		        				{		        					
		        					btDl.setText(Character.toString(_displayText.charAt(j)));
		        					//btDl.startAnimation(_myAnimation);
		        					
		        					btn1.setVisibility(View.INVISIBLE);
		        					updateResult();
		        					maddword.start();
		        				}
		        				break;
		        			}
		        			
		        		}
		        		
		        	}
		        	catch(SecurityException e)
		        	{
		        		
		        	}
		     
		        }
		    });
		    
		    iCol += 1;
		}
		
				
	}
	
	private void updateResult(){
		
		if(_displayText.contains("0"))		
		{
			return;
		}
		
		if (_displayText.equalsIgnoreCase(_expectText))
		{
			
			_currentScore += 4;
			saveIndex(_nextIndex);
			
			displayScoreDialog();
		}
		else
		{
    		for(int j =0; j < _displayText.length(); j++)
    		{
				Button btDl = ((Button) findViewById(j));
				if (btDl != null)
				{	
					btDl.startAnimation(_myAnimation);
				}
    		} 
			
		}
		
	}
	
	private void RemoveButtons(){
		for(int j =0; j < _expectText.length(); j++)
		{        				
			Button btDl = ((Button) findViewById(j));
			displayTest_layout.recomputeViewAttributes(btDl);
			displayTest_layout.removeView(btDl);
			
		}
		
		for(int j =0; j < _suggestionText.length(); j++)
		{        				
			Button btDl = ((Button) findViewById(j + 100));
			if (btDl != null)
			{
				displayTest_layout.recomputeViewAttributes(btDl);
				displayTest_layout.removeView(btDl);				
			}
		}
	}
	
	
	private String setCharAtIndex(String strIn, int idx, char newchar){
		
		if (idx < strIn.length() - 1)
			return strIn.substring(0,idx) + newchar + strIn.substring(idx+ 1);
		if(idx == strIn.length() - 1)
			return strIn.substring(0,idx) + newchar;  
		return strIn;
		
	}
	
	private void displayScoreDialog()
	{
		Intent i=new Intent(this,ScoreActivity.class);
		startActivityForResult(i, REQUEST_CODE_SC);
		
	}
    ///////////////////////////////////////////////////////////////////
    
    
    
    
    //////////facebook section/////////////////////////////////////////////
	public Bitmap takeScreenshot() {
		   View rootView = findViewById(android.R.id.content).getRootView();
		   rootView.setDrawingCacheEnabled(true);
		   return rootView.getDrawingCache();
		}


    private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if (pendingAction != PendingAction.NONE &&
                (exception instanceof FacebookOperationCanceledException ||
                exception instanceof FacebookAuthorizationException)) {
                new AlertDialog.Builder(PlayActivity.this)
                    .setTitle(R.string.cancelled)
                    .setMessage(R.string.permission_not_granted)
                    .setPositiveButton(R.string.ok, null)
                    .show();
            pendingAction = PendingAction.NONE;
        } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
            handlePendingAction();
        }
        updateUI();
    }
    

    private void updateUI() {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());
        _postPhotoButton.setEnabled(enableButtons || _canPresentShareDialogWithPhotos);
    }

    @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        // These actions may re-set pendingAction if they are still pending, but we assume they
        // will succeed.
        pendingAction = PendingAction.NONE;

        switch (previouslyPendingAction) {
            case POST_PHOTO:
                postPhoto();
                break;
        }
    }

    private interface GraphObjectWithId extends GraphObject {
        String getId();
    }

    private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
        String title = null;
        String alertMessage = null;
        if (error == null) {
            title = getString(R.string.success);
            String id = result.cast(GraphObjectWithId.class).getId();
            alertMessage = getString(R.string.successfully_posted_post, message, id);
        } else {
            title = getString(R.string.error);
            alertMessage = error.getErrorMessage();
        }

        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(alertMessage)
                .setPositiveButton(R.string.ok, null)
                .show();
    }

    private void onClickPostPhoto() {
        performPublish(PendingAction.POST_PHOTO, _canPresentShareDialogWithPhotos);
    }

    private FacebookDialog.PhotoShareDialogBuilder createShareDialogBuilderForPhoto(Bitmap... photos) {
        return new FacebookDialog.PhotoShareDialogBuilder(this)
                .addPhotos(Arrays.asList(photos));
    }

    private void postPhoto() {
        Bitmap image = takeScreenshot();
        		//BitmapFactory.decodeResource(this.getResources(), R.drawable.iscore);
        if (_canPresentShareDialogWithPhotos) {
            FacebookDialog shareDialog = createShareDialogBuilderForPhoto(image).build();
            uiHelper.trackPendingDialogCall(shareDialog.present());           
        } else if (hasPublishPermission()) {
            Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), image, new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    showPublishResult(getString(R.string.photo_post), response.getGraphObject(), response.getError());
                }
            });
            request.executeAsync();
        } else {
            pendingAction = PendingAction.POST_PHOTO;
        }
    }


    private void showAlert(String title, String message) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(R.string.ok, null)
                .show();
    }

    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions");
    }

    private void performPublish(PendingAction action, boolean allowNoSession) {
        Session session = Session.getActiveSession();
        if (session != null) {
            pendingAction = action;
            if (hasPublishPermission()) {
                // We can do the action right away.
                handlePendingAction();
                return;
            } else if (session.isOpened()) {
                // We need to get new permissions, then complete the action when we get called back.
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
                return;
            }
        }

        if (allowNoSession) {
            pendingAction = action;
            handlePendingAction();
        }
    }
    
    //end facebook section///////////////////////////////////
    
   
    /** Called when the Load Interstitial button is clicked. */
    public void loadInterstitial() {    
  //.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
      // Check the logcat output for your hashed device ID to get test ads on a physical device.
      AdRequest adRequest = new AdRequest.Builder()
      	.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
          .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
          .build();

      // Load the interstitial ad.
      interstitialAd.loadAd(adRequest);
    }

    /** Called when the Show Interstitial button is clicked. */
    public void showInterstitial() {
      if (interstitialAd.isLoaded()) {
    	  Log.d(LOG_TAG, "ad showing.");
        interstitialAd.show();
      } else {
        Log.d(LOG_TAG, "Interstitial ad was not ready to be shown.");
      }
    }

    /** Gets a string error reason from an error code. */
    private String getErrorReason(int errorCode) {
      String errorReason = "";
      switch(errorCode) {
        case AdRequest.ERROR_CODE_INTERNAL_ERROR:
          errorReason = "Internal error";
          break;
        case AdRequest.ERROR_CODE_INVALID_REQUEST:
          errorReason = "Invalid request";
          break;
        case AdRequest.ERROR_CODE_NETWORK_ERROR:
          errorReason = "Network Error";
          break;
        case AdRequest.ERROR_CODE_NO_FILL:
          errorReason = "No fill";
          break;
      }
      return errorReason;
    }
    
    
    
    /** Called when the refresh button is clicked. */
    public void refreshAd(View unusedView) {
      if (adView != null) {
        adView.loadAd(new PublisherAdRequest.Builder().build());
      }
    }
    
    
    
}
